package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.admin.vo.HeaderFieldsVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.file.service.IGeneralFileService;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ChildCompanyAddDTO;
import org.jsola.hr.dto.ChildCompanyUpdateDTO;
import org.jsola.hr.query.ChildCompanyQuery;
import org.jsola.hr.query.HrEmployeeSalaryNewQuery;
import org.jsola.hr.query.HrEmployeeSalaryQuery;
import org.jsola.hr.query.HrMonthlySalaryQuery;
import org.jsola.hr.service.IChildCompanyService;
import org.jsola.hr.service.IGroupCompanyService;
import org.jsola.hr.vo.*;
import org.jsola.salary.vo.EmployeeDetailsNewVO;
import org.jsola.salary.vo.EmployeeDetailsVO;
import org.jsola.salary.vo.SalaryTemplateItemVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * 用工单位分组
 *
 * @author zhr
 */
@RestController("hrChildCompanyController")
@RequestMapping(HrConstants.API_PATH + "/v1/childrenCompany")
public class ChildCompanyController implements IChildCompanyControllerAPI {

    @Autowired
    private IChildCompanyService childCompanyService;

    @Autowired
    private IGroupCompanyService groupCompanyService;

    @Autowired
    private IGeneralFileService generalFileService;

    @Override
    @GetMapping(value = "/{childCompanyId}")
    public Result<ChildCompanyVO> findById(@PathVariable String childCompanyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看用工单位分组权限校验

        return Result.success(
                childCompanyService.selectById(childCompanyId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/findChildAndRelation/{childCompanyId}")
    public Result<ChildCompanyVO> findChildAndRelationById(@PathVariable String childCompanyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看子公司信息权限校验

        return Result.success(
                childCompanyService.selectChildCompanyAndRelationById(childCompanyId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<ChildCompanyListVO>> listAll(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看用工单位分组权限校验

        return Result.success(
                childCompanyService.select(childCompanyQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listAll/list")
    public Result<List<ChildCompanyListVO>> listAllList(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看用工单位分组权限校验

        return Result.success(
                childCompanyService.selectList(childCompanyQuery, tokenUser)
        );
    }


    @Override
    @GetMapping
    public Result<Page<ChildCompanyListVO>> page(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                childCompanyService.selectPage(childCompanyQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/tree")
    public Result<List<ChildCompanyVO>> tree(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                childCompanyService.tree(childCompanyQuery, tokenUser)
        );
    }


    @Override
    @PostMapping(value = "/saveChildAndRelation")
    public Result<ChildCompanyVO> saveChildAndRelation(@Valid @RequestBody ChildCompanyAddDTO childCompanyAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增子公司信息权限校验 用工单位分组支持无限级

        return Result.success(
                childCompanyService.saveChildCompanyAndRelation(childCompanyAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping(value = "/updateChildAndRelation")
    public Result<Integer> updateChildAndRelation(@Valid @RequestBody ChildCompanyUpdateDTO childCompanyUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改子公司信息权限校验

        int count = childCompanyService.updateChildCompanyAndRelation(childCompanyUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping(value = "/deleteChildAndRelation/{childCompanyId}")
    public Result<Integer> deleteChildAndRelation(@PathVariable String childCompanyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除子公司信息权限校验

        int count = childCompanyService.deleteChildCompanyAndRelation(childCompanyId, tokenUser);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping("/selectByUserId")
    public Result<UserCompanyVO> selectByUserId(@Valid String userId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                childCompanyService.selectByUserId(userId, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/selectMonthlySalaryByCompanyList")
    public Result<List<HrMonthlySalarySummaryVO>> selectMonthlySalaryByCompanyList(
            @Valid @RequestBody HrMonthlySalaryQuery hrMonthlySalaryQuery) {

        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                childCompanyService.selectMonthlySalaryByCompanyList2(hrMonthlySalaryQuery, tokenUser)
        );
    }


    @Override
    @GetMapping("/selectUsedTemplateByCompanyList")
    public Result<List<SalaryTemplateItemVO>> selectUsedTemplateByCompanyList(@Valid Integer yearly, Integer monthly
            , String type, String id) {

        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                childCompanyService.selectUsedTemplateByCompanyList(yearly, monthly, type, id, tokenUser)
        );
    }


    @Override
    @PostMapping("/selectEmployeeSalaryByCompanyIds")
    public Result<Page<EmployeeDetailsVO>> selectEmployeeSalaryByCompanyIds(
            @Valid @RequestBody HrEmployeeSalaryQuery hrEmployeeSalaryQuery) {

        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                childCompanyService.selectEmployeeSalaryPageByCompanyIds(hrEmployeeSalaryQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/export")
    public ResponseEntity<Resource> export(@Valid @RequestBody HrEmployeeSalaryQuery hrEmployeeSalaryQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        String excelFilePath = childCompanyService.exportExcel(hrEmployeeSalaryQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }


    @PostMapping("/exportByUrl")
    public Result<String> exportByUrl(@Valid @RequestBody HrEmployeeSalaryQuery hrEmployeeSalaryQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        String excelFilePath = childCompanyService.exportExcel(hrEmployeeSalaryQuery, tokenUser);
        // 编码文件名，防止乱码
//        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        //把文件上传到OSS中，返回下载路径
//        File file = new File(excelFilePath);
//        MultipartFile resultMultipartFile = FileUtil.toMultipartFile(file);
//        MultipartFile[] files = {resultMultipartFile};
//        List<String> pathList = siteFileService.uploadDiffSite(files, "inline", tokenUser);
        List<String> list = new ArrayList<>();
        list.add(excelFilePath);
        List<String> pathList = generalFileService.upload(list, "inline");
        if (CollectionUtils.isEmpty(pathList) || pathList.size() == 0) {
            Result.fail();
        }
        return Result.success(pathList.get(0));
    }

    @Override
    @PostMapping("/selectHeaderDetail")
    public Result<HeaderFieldsVO> selectHeaderDetail(@Valid @RequestBody HrEmployeeSalaryQuery hrEmployeeSalaryQuery) {

        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                childCompanyService.selectHeaderDetail(hrEmployeeSalaryQuery.getType(), hrEmployeeSalaryQuery.getId()
                        , hrEmployeeSalaryQuery.getCustomerDetailsIdList(), hrEmployeeSalaryQuery.getYearly()
                        , hrEmployeeSalaryQuery.getMonthly(), tokenUser)
        );
    }

}

